package com.jty.module_user.ui.fragment

import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.arialyy.aria.core.Aria
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.SnackbarUtils
import com.bumptech.glide.Glide
import com.czl.lib_base.config.AppConstants
import com.gyf.immersionbar.ImmersionBar
import com.jty.lib_base.base.BaseFragment
import com.jty.lib_base.extension.loadDefault
import com.jty.lib_base.extension.loadImage
import com.jty.lib_base.extension.loadPhotoUrl
import com.jty.lib_base.utils.DayModeUtil
import com.jty.lib_base.utils.PermissionUtil
import com.jty.lib_base.utils.getLocalAvatarPath
import com.jty.module_user.BR
import com.jty.module_user.R
import com.jty.module_user.databinding.UserFragmentUserBinding
import com.jty.module_user.viewmodel.UserViewModel
import com.lxj.xpopup.util.XPermission
import com.orhanobut.logger.Logger
import java.io.File

@Route(path = AppConstants.Router.User.F_USER)
class UserFragment : BaseFragment<UserFragmentUserBinding,UserViewModel>(),
    NetworkUtils.OnNetworkStatusChangedListener {
    override fun initContentView(): Int {
        return R.layout.user_fragment_user
    }

    override fun initVariableId(): Int {
        return BR.viewModel
    }


    override fun useBaseLayout(): Boolean {
        return true
    }

    override fun onSupportVisible() {
        ImmersionBar.with(this).fitsSystemWindows(true)
            .statusBarDarkFont(!DayModeUtil.isNightMode(requireContext())).init()
    }

    override fun initData() {
        super.initData()
        if (!NetworkUtils.isConnected()){
            showNetErrorBar()
        }


        NetworkUtils.registerNetworkStatusChangedListener(this)
    }

    override fun initViewObservable() {
        super.initViewObservable()
        viewModel.uc.clickToF.observe(this){
            Logger.i("界面 F = ${it}")
        }

        viewModel.userInfoBean.observe(this){
            refreshUI()
        }

        viewModel.uc.refreshUserInfoEvent.observe(this){
            viewModel.userInfoBean.postValue(it)
        }
    }

    private fun refreshUI() {
        Logger.i("refreshUI=${viewModel.userInfoBean.value.toString()}")
        if (!viewModel.userInfoBean.value?.avatarUrl.isNullOrBlank()){
            val path = getLocalAvatarPath(viewModel.userInfoBean.value?.avatarUrl!!.trim())
            if (!File(path).exists()){
                PermissionUtil.reqStorage(fragment=this, callback = { allGranted, _, _ ->
                    Aria.download(this).load(viewModel.userInfoBean.value?.avatarUrl!!.trim()).setFilePath(path).create()
                })
                binding.cHead.loadImage(viewModel.userInfoBean.value?.avatarUrl!!.trim())
            }else{
                path.let { binding.cHead.loadImage(it)}
            }
        }else{
            binding.cHead.loadDefault(requireContext().getDrawable(R.drawable.base_man)!!)
        }

    }


    private fun showNetErrorBar() {
        SnackbarUtils.with(binding.clRoot).setDuration(SnackbarUtils.LENGTH_INDEFINITE)
            .setBgColor(ContextCompat.getColor(requireContext(), R.color.md_red_600))
            .setMessage("网络已断开，请重新连接").show(true)
    }

    override fun onDisconnected() {
        showNetErrorBar()
    }

    override fun onConnected(networkType: NetworkUtils.NetworkType?) {
        SnackbarUtils.dismiss()
        // 重新联上网并且第一次未加载成功 避免每次断网重连都请求一次消耗流量
        if (NetworkUtils.isConnected()) {

        }
    }

    override fun onDestroyView() {
        NetworkUtils.unregisterNetworkStatusChangedListener(this)
        super.onDestroyView()
    }
}